package com.spagettikod.t437.component.domain;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import com.spagettikod.t437.simpledb.SimpleDBDomain;

public class DomainJListPopupListener extends MouseAdapter {

	private DomainJList domainJList;

	private DomainJListJPopupMenu popup;

	public DomainJListPopupListener(DomainJListJPopupMenu popup) {
		this.popup = popup;
	}

	private void initEvent(MouseEvent e) {
		domainJList = (DomainJList) e.getSource();
	}

	public void mousePressed(MouseEvent e) {
		initEvent(e);
		maybeShowPopup(e);
	}

	public void mouseReleased(MouseEvent e) {
		initEvent(e);
		if (e.getButton() == MouseEvent.BUTTON3 && insideListItem(e)) {
			int index = domainJList.locationToIndex(e.getPoint());
			domainJList.setSelectedIndex(index);
		}
		maybeShowPopup(e);
	}

	public void mouseClicked(MouseEvent e) {
		initEvent(e);
		if (e.getClickCount() == 2 && insideListItem(e)) {
			int index = domainJList.locationToIndex(e.getPoint());
			SimpleDBDomain domain = domainJList.getDomainAt(index);
			domainJList.fireDomainDoubleClickEvent(domain);
		}
	}

	private void maybeShowPopup(MouseEvent e) {
		if (e.isPopupTrigger()) {
			if (insideListItem(e)) {
				popup.enableNewMenuItem(true);
				popup.enableExportMenuItem(true);
				popup.enableDeleteMenuItem(true);
			} else {
				popup.enableNewMenuItem(true);
				popup.enableExportMenuItem(false);
				popup.enableDeleteMenuItem(false);
				domainJList.clearSelection();
			}
			popup.showPopupMenu(e.getComponent(), e.getX(), e.getY());
		}
	}

	/**
	 * Makes sure the event was triggered inside a list item and not outside an
	 * item.
	 * 
	 * @param e
	 * @return true if the click occured on top of a list item otherwise false.
	 */
	private boolean insideListItem(MouseEvent e) {
		int index = domainJList.locationToIndex(e.getPoint());
		int itemTop = domainJList.indexToLocation(index).y;
		int itemBottom = itemTop + domainJList.getFixedCellHeight();
		int event = e.getY();
		return (event >= itemTop && event <= itemBottom);
	}
}
